/* udm is freely distributable under the terms of GPL license.
*  For details, see umbacos web site: http://umbacos.altervista.org/udm
*  or write at umbacos@gmail.com
*--------------------------------------------------------------------------*/
//////////////////////
// REGISTER objects //
var register = { track : Math.random(), changeTrack: function () { return this.track=Math.random(); } };
var reg_amu  = { track : Math.random(), changeTrack: function () { return this.track=Math.random(); } };

////////////////
// LOG object //
var log = {
	out: $empty, area: null, register: null, loglines: null,
	clear:  function (){ this.area.value = ""; },
	toggle: function (){ (this.log!=this.out ? this.out=this.log : this.out=$empty); },
	debug:  function() {return (location.href.indexOf('debug')>0)},
	log:    function (f,t) {
		var a = this.area.value + ((new Date()).getTime() + ' - ' + this.register.track + ' - ' + f + '\t' + t + '\n');
		this.area.value = a.substr(a.length-parseInt(this.loglines.value));
		},
	init:   function (reg) {
		if (this.debug()) {
			this.out = this.log;
			this.register = reg;
			this.area = new Element('textarea',{ cols: '100', rows: '30', id: 'tlogger'});
			this.loglines = new Element('input',{ id: 'loglines', type: 'text', 'value': '4000' });
			$('bdy').adopt([ (new Element('button',{ 'text': 'CLEAR LOG' })).addEvent('click',this.clear.bind(this)),
					 (new Element('button',{ 'text': 'TOGGLE LOG' })).addEvent('click',this.toggle.bind(this)),
					 this.loglines, ( new Element('br')), this.area ]);
			}
		}
}
/////////////////
// TREE object //
var uTree = {
	selectedBackgroundColor : 'lightgreen',
	selectedColor : 'black',
	imgClosed : 'url(images/closed.png) no-repeat left top',
	imgOpen : 'url(images/open.png) no-repeat left top',
	selected : new Array(),
	noBubble : function(e){ (typeof e!="undefined") ? e.stopPropagation() : event.cancelBubble=true; },
	init : function(t, options) {
		tt = $(t);
		if (!tt) return null;
		tt.className='utree';
		tt.getElements('ul').each( function(ulel) {
			uTree.build(tt, ulel);
			});
		uTree.open(tt.getElement('ul'));
		return tt;
	},
	build : function (t, ulel) {
		ulel.parentNode.className='submenu';

		if ( ! ulel.get('rel') )		uTree.close(ulel);
		else if (ulel.get('rel')=='open')	uTree.expand(t, ulel);

		$(ulel.parentNode).addEvent('click', function(e){
			if (e.target.id) {
				uTree.select(e.target);
				return uTree.noBubble(e);
				}
			var submenu=this.getElement('ul');
			if (submenu.get('rel') == 'closed')	uTree.open(submenu);
			else					uTree.close(submenu);
			uTree.noBubble(e)
			});
		ulel.addEvent('click', function(e){
			if (e.target.id) {
				uTree.select(e.target);
				return uTree.noBubble(e);
				}
			uTree.noBubble(e)
			});
	},
	select : function (uspan) {
		uspan.style.backgroundColor = uTree.selectedBackgroundColor;
		uspan.style.color = uTree.selectedColor;
		if (uTree.selected[uspan.className]) {
			uTree.selected[uspan.className].style.backgroundColor = '';
			uTree.selected[uspan.className].style.color = '';
			}
		uTree.selected[uspan.className] = uspan;
		$(uspan.className).value = uspan.id;
		return uspan;
	},
	open : function (ulel) {
		if (ulel) {
			ulel.show();
			ulel.set('rel', 'open');
			ulel.parentNode.style.background = uTree.imgOpen;
			}
		return ulel;
	},
	close : function (ulel) {
		if (ulel) {
			ulel.hide();
			ulel.setAttribute('rel', 'closed')
			ulel.parentNode.style.background = uTree.imgClosed;
			}
		return ulel;
	},
	expand : function(rootnode, currentnode){
		while (currentnode!=rootnode){
			if (currentnode.tagName=='ul')
				uTree.open(currentnode);
			currentnode=currentnode.parentNode
		}
		return rootnode;
	},
	flatten : function(t, action){
		t.getElements('ul').each( function (ulel) {
			if (action=='expand') 	uTree.open (ulel);
			else			uTree.close (ulel);
		});
		return t;
	}
}
//////////////////
// POPUP object //
var Popup = {
	init: function (el) {
		el.close = Popup.close.bind(el);	el.show = Popup.show.bind(el);
		el.place = Popup.place.bind(el);	el.focus = Popup.focus.bind(el);
		el.fixUnfix = Popup.fixUnfix.bind(el);	el.hide = Popup.hide.bind(el);
		new Drag(el,{handle: el.getElement('.btnMovePop')});
		el.getElement('.btnClose').addEvent('click', el.hide);
		el.getElement('.btnPinPop').addEvent('click', el.fixUnfix);
	},
	place: function place() {
		this.unpin();
		this.position();
		this.fade('in');
		if (this.getPosition().y < window.getScroll().y)
			this.style.top= (window.getScroll().y + 10) + 'px';
		this.pin();
		var f = this.getElement('.setfocus');
		if (f) Popup.focus.delay(400,f);
	},
	close:	function (e){ if (( e.key == 'enter' ) || ( e.key == 'esc' )) this.hide(); },
	show:	function show() { Popup.hideAll();
				this.place.delay(20,this);
				initAnimate(this,'smallimg');
				iniTips(); },
	focus:	function focus(){ $try(this.focus); },
	fixUnfix: function() { this.togglepin(); },
	hide:	function () { this.unpin(); this.fade('out'); (function(){if (this.style.visibility=='hidden') this.style.top='-1000px'}).bind(this).delay(2000); },
	hideAll:function () { $$('table.pop_up').each(function (el){ if (el.style.visibility=='visible') el.hide(); }); }
}
////////////////////
// STORAGE object //
var Storage = {
	write: function (k, v) { Cookie.write(k, v, {duration: 10000}); },
	read:  function (k)    { return Cookie.read(k); },
	monitor:function (fld)  {
		var k = (fld.id != '' ? fld.id : fld.className.split(' ')[0]);
		var v = Storage.read(k);
		if (fld.hasClass('field_check')) {
			if ($defined(v))	fld.checked = (v != "false");
			else			Storage.write(k, fld.checked);
		} else {
			if ($defined(v))	fld.value = v;
			else	Storage.write(k, fld.value);
		}
		fld.addEvent  ('change', Storage.change.bind(fld));
		return fld;
		},
	change: function () {
		var k = (this.id != '' ? this.id : this.className.split(' ')[0]);
		var v = (this.hasClass('field_check') ? this.checked : this.value);
		Storage.write(k, v);
		if (this.hasClass('refresh')) {
			log.out('Storage.change', 'this.hasClass("refresh") - calling m_readData');
			m_readData();
			}
		},
	reset: function() {
		document.cookie.split(';').each( function(c) {
			Storage.write(c.split('=')[0].trim(),'');
			Cookie.dispose(c.split('=')[0].trim());
			$('openconf').set('src', IMG_SPINNER);
			Popup.hideAll();
			popMsg.delay(2500, null, 'To complete the reset operation, please close the browser and reopen it');
			(function () { $('openconf').set('src', IMG_CONF)}).delay(2500, null, 'To complete the reset operation, please close the browser and reopen it');
		});
}}
////////////////////
// POPUP builders //
function popConfirm(e, msg, cmd, myID) {
	var info= '<br><pre class=pop_in>' + msg.replace('$$$', myID) + '</pre><br>';
	info += '<div class="center"><button id=bcancel class=btnCancel></button>&nbsp;&nbsp;<button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mtain.getElement('.btnOk').addEvent('click', m_ajax.pass(['cmd=' + cmd + '&file=' + escape(myID),this]));
	h_mta.show();
}
function popReset() {
	var info= '<br><pre class=pop_in>Reset to defaults?</pre><br>';
	info += '<div class="center"><button id=bcancel class=btnCancel></button>&nbsp;&nbsp;<button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mtain.getElement('.btnOk').addEvent('click', Storage.reset);
	h_mta.show();
}
function popBackup() {
	var info='<br>';
	$$('.persist').each( function (fld) {
		info += fld.get('id') + '=';
		if (fld.hasClass('field_check')) info += fld.checked;
		else				 info += fld.value;
		info += '<br>';
		});
	info += '<div class="center"><button id=bcancel class=btnCancel></button>&nbsp;&nbsp;<button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
}
function popRename(e) {
	var myID=this.id.substr(0,this.id.length-2);
	var info= '<br><pre class=pop_in>Rename \"' + myID + '\"?</pre>';
	info += '<input type=text id=newi style="width: 100%" class=setfocus><br><br>';
	info += '<div class="center"><button class="btnCancel" id=bcancel></button>&nbsp;&nbsp;';
	info += '<button class=btnOk id=bok></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.setfocus').set('value',myID);
	h_mtain.getElement('.setfocus').addEvent('keypress', doSubmit);
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mtain.getElement('.btnOk').addEvent('click', doRename.pass(['rename', myID, $('newi')]));
	h_mta.show();
}
function popCmd(e) {
	h_mtain.set('html', $('div_cmd').get('html'));
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	Storage.monitor(h_mtain.getElement('.setfocus')).addEvent('keypress', doCmd);
	m_request('scripts', '', 'scripts', ZCMD, function(t) { h_mtain.getElement('#selcmd').set('html','<option value="">a script from here</option>' + t); });
	h_mtain.getElement('#goscript').addEvent('click', doScript);
	h_mta.show();
}
function popMkdir(e) {
	var info= '<br><pre class=pop_in>Create new directory</pre>';
	info += '<input type=text id=newi style="width: 100%" class="setfocus"><br><br>';
	info += '<div class="center"><button class="btnCancel"></button>&nbsp;&nbsp;<button class="btnOk"></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.setfocus').addEvent('keypress', doSubmit);
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mtain.getElement('.btnOk').addEvent('click', doMkdir.pass(['mkdir', $('newi')]));
	h_mta.show();
}
function popError(t){ popMsg('ERROR:<BR>' + t); }
function popMsg(t){
	var info= '<br><pre class=pop_in>' + t + '</pre><br>';
	info += '<div class="center"><button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', info);
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
}
function popCtor(t) {
	var tt = JSON.decode.attempt(t);
	if (!tt) return popError(t);
	var intro = '<center><table><tr><td class=pop_gr>';
	intro += 'Torrent:<br><input type=text disabled id=ct_fil size=65 value="' + tt.file.replace('"','\\"') + '"><br>'
	tt=tt.benc;
	if (tt['info']) {
		if (tt.info.name) intro += 'Save as:<br><input type=text rel="ctorSaveAs" class="field" size="65" value="' + tt.info.name.replace('"','\\"') + '"><br>'
		if (tt.info.length) intro += ' Size: ' + m_humanReadable(tt.info.length) + '<br>';
		if (tt.info.files) {
			intro += '<br>Select files to download:<br><div style="width:100%;height:300px;overflow:auto"><table>'
			tt.info.files.each( function(f,idx) {
				intro += '<tr><td><input type=checkbox class=field_file value=' + (idx+1) + ' id=ct_' + idx + ' checked></td><td class=pop_gr>'
				f.path.each( function(p) { intro += '/'+ p; } );
				intro += '</td><td class=pop_gr>[</td><td class="pop_gr right">' + m_humanReadable(f.length) + '</td><td class=pop_gr>]</td></tr>'
				});
			intro += '</table></div><br>'
			intro += '<img src="images/selectall.png" onclick="chkSwitch(true);"> '
			intro += '<img src="images/unselectall.png" onclick="chkSwitch(false);"> '
			}
		}
	intro += '</td></tr><tr><td class="pop_gr right">' + $('div_ctor_pre').get('html') + '</td></tr></table></center>';
	intro += '<div id=div_opt style="display: none; text-align:right">' + $('div_ctor_template').get('html') + '</div>';

	h_mtain.set('html',intro);
	m_setDefaults();
	$('ct_u').value = tt.announce;

	h_mtain.getElement('.btnGo').addEvent('click', m_composeCmdLine.pass(['ctor','ct_fil']));
	h_mtain.getElement('.btnOpt').addEvent('click', function () { $('div_opt').toggle(); h_mta.place.delay(20,h_mta); });
	h_mta.show();
	initAnimate(h_mta,'smallimg');
	this.set('src', IMG_PLAY);
}
function chkSwitch(wha){$$('.field_file').each(function(el){el.checked=wha})}
function popDisk(t){
	h_mtain.set('html', '<br><pre class=pop_in>' + t + '</pre><br>' +
		'<div class="center"><button id=bok class="btnOk setfocus"></button></div><br>');
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
	this.set('src',IMG_DISK);
}
function popMeta(t) {
	var tt = JSON.decode.attempt(t);
	if (!tt) return popError(t);
	var pre= '<tr><td class=pop_gr>'; var sep='</td><td class=pop_gr>'; var pst ='</td></tr>';
	var intro = '<center><table width=600>';
	intro += pre + '<b>Torrent:</b>' + sep + '<b>' + tt.file + '</b>' + pst
	tt=tt.benc;
	if (tt['announce']) 		intro += pre + 'Announce:' + sep + tt.announce + pst
	if (tt['creation date']) 	intro += pre + 'Creation date:' + sep + new Date(tt['creation date']*1000) + pst
	if (tt['comment']) 		intro += pre + 'Comment:' + sep + tt['comment'] + pst
	if (tt['created by']) 		intro += pre + 'Created by:' + sep + tt['created by'] + pst
	if (tt['info']) {
		if (tt.info.name) 	intro += pre + 'Name:' + sep + tt.info.name + pst
		if (tt.info.length) 	intro += pre + 'Size:' + sep + m_humanReadable(tt.info.length) + pst
		if (tt.info.files) {
			intro += pre + 'Contained files:' + sep + pst;
			intro += '<tr><td colspan=2 class=pop_gr><div style="width:100%;height:300px;overflow:auto"><table>'
			tt.info.files.each( function(f,idx) {
				intro += '<tr><td class=pop_gr>&lt;' + (idx+1) + '&gt;</td><td class=pop_gr>'
				f.path.each( function(p) { intro += '/'+ p; } );
				intro += '</td><td class=pop_gr>[</td><td class="pop_gr right">' + m_humanReadable(f.length) + '</td><td class=pop_gr>]</td></tr>'
				});
			intro += '</table></div>' + pst;
			}
		}
	intro += '</table></center><br>';
	intro += '<div class="center"><button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', intro );
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
	this.set('src', IMG_METAINFO);
}
function popOpts (tt) {
	t = tt.split('\n');
	var intro = '<br><pre>Operating on: \n' + t[1];
	intro += '\n\nCommand line options\n' + t[2];
	intro += '</pre><br><br>';
	intro += '<div class="center"><button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', intro );
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
	this.set('src', IMG_METAINFO);
}
function popLock(t) {
	if (t=='OK') {
		var intro = '<br><img src="images/lockok.png" class="middle"> Disable Basic Authentication?<br><br>';
		intro += '<div class="center"><button id=bok class="btnSet setfocus"></button></div><br>';
		$('sec_in').set('html', intro );
		$('sec_in').getElement('.btnSet').addEvent('click', m_request.pass(['lock', 'unlock', 'lock', ZCMD, popMsg]));
	} else {
		var intro = '<br><img src="images/lockok.png" class="middle"> Insert Username and Password to enable Basic Authentication<br>';
		intro += '<br><b>Username: </b><input id="usn"><br><br><b>Password: </b><input type=password id="psd"><br><br>';
		intro += '<br><b>protect also the <a href="' + ZCMD+ '?cmd=fb" target=_blank style="color: white">File Browser</a>: </b><input type=checkbox checked id="ufb"><br><br>';
		intro += '<br>and keep in mind this is just Basic Authentication...<br><br>';
		intro += '<div class="center"><button id=bok class="btnSet setfocus"></button></div><br>';
		$('sec_in').set('html', intro );
		$('sec_in').getElement('.btnSet').addEvent('click', doLock.bind(this));
	}
}
function popTree(t) {
	if (!d_tree) d_tree=t;
	var intro = '<br><b>Select the destination folder:</b><br><br><div style="width:100%;height:300px;overflow:auto">' + d_tree + '</div><br>';
	intro += '<div class="center"><button class="btnCancel" id=bcancel></button>&nbsp;&nbsp;<button id=bok class="btnOk setfocus"></button></div><br>';
	h_mtain.set('html', intro );
	$('viewtree').set('src', IMG_TREE);
	if (!uTree.init($('treepop'))) {
		popError(d_tree);
		return d_tree=null;
	}
	h_mtain.getElement('.btnOk').addEvent('click', doChdir.pass($('treepop')));
	h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
	h_mta.show();
}
function popMove(t) {
	if (!d_tree) d_tree=t;
	var intro = '<br><b>Select the destination folder for ' + curDir + h_t + ':</b><br><br><div style="width:400px;height:300px;overflow:auto">' + d_tree + '</div><br>';
	intro += '<div class="center"><button id=bcancel class="btnCancel setfocus"></button>&nbsp;&nbsp;<button id=bmove class="btnMove"></button>&nbsp;&nbsp;<button id=bcopy class="btnCopy"></button></div><br>';
	h_mtain.set('html', intro );

	if (!uTree.init($('treepop'))) {
		popError(d_tree);
		d_tree=null;
	} else {
		h_mtain.getElement('.btnMove').addEvent('click', doRename.pass(['rename', h_t, $('treepop')]));
		h_mtain.getElement('.btnCopy').addEvent('click', doRename.pass(['copy', h_t, $('treepop')]));
		h_mtain.getElement('.btnCancel').addEvent('click', h_mta.hide);
		h_mta.show();
	}
	$(h_t + '_V').set('src', IMG_MOVETO);
}
function popWget() {
	var intro = $('div_wget_pre').get('html');
	intro += '<div id=div_opt style="display: none;">' + $('div_wget_template').get('html') + '</div>';
	h_mta.visibility='hidden';
	h_mtain.set('html',intro);
	m_setDefaults();
	$('wg_file_ok').value = $('wg_file').value;
	h_mtain.getElement('.btnGo').addEvent('click', m_composeCmdLine.pass(['wget','wg_file_ok']));
	h_mtain.getElement('.btnOpt').addEvent('click', function () { $('div_opt').toggle(); h_mta.place.delay(20,h_mta); });
	h_mta.show();
	initAnimate(h_mta,'smallimg');
}
function popMu() {
	var intro = $('div_mu').get('html');
	h_mta.visibility='hidden';
	h_mtain.set('html',intro);
	h_mtain.getElement('.btnMu').addEvent('click', doMu);
	h_mta.show();
	initAnimate(h_mta,'smallimg');
}
function popAmule(){
	h_mta.visibility='hidden';
	h_mtain.set('html',$('div_amule').get('html'));
	h_mtain.getElement('.setfocus').addEvent('keypress', doCmd)
	h_mtain.getElement('#amustop').addEvent('click', m_request.pass(['run','test "$(ps -ef|grep amule|grep -v grep)" && amulecmd -c shutdown || amuled -f','run',ZCMD,doCmd]));
	h_mtain.getElement('.btnOk').addEvent('click', h_mta.hide);
	h_mta.show();
	m_request('amule', 'help', 'amule', ZCMD, doCmd);
}
function m_setDefaults(){
	h_mtain.getElements('input').each( function (fld) {
		if (d = h_conf.getElement("#" + fld.get('rel'))) {
			if (fld.hasClass('field_check')) fld.checked = d.checked;
			else				 fld.value = d.value;
			}
		})
}
function buildDnlList(tt) {
	var jj = JSON.decode.attempt(tt);
	if (!jj) return popError(tt);
	if (h_disk) h_disk.set('text', jj.disk.perc);
	if (!jj.dnl) return jj;
	if (jj.curdir != curDir) {
		b_chdir=true;
		curDir=jj.curdir;
	}
	if (b_chdir) {
		h_bDnl.empty();
		h_sCur.set('text',curDir);
	} else {
		h_bDnl.getChildren().each( function(ch) {
			var myID = ch.id.substr(0,ch.id.length-3)
			if ((myID != '_up') && (tt.indexOf("'" + myID + "'") < 0))
				ch.destroy();
			} );
	}

	if (b_chdir || (curDir == '/')) {
		if ( partr ) partr.destroy();
		partr = null;
		}

	if ((curDir != '/') && (!partr)) {
		var parDir;
		for (var i = 0; i < curDir.length - 2; i++)
			if (curDir.charAt(i) == '/')
				parDir=curDir.substr(0, i+1);
		partr = new Element('tr', {id : '_up_tr'}).addEvent('mouseover', fx_hide);
		var mTd_type = new Element('td', {'class': 'center'});
		var mTd_file = new Element('td', {'class': 'left'});
		var mTd_date = new Element('td', {'class': 'right'});
		var mTd_size = new Element('td', {'class': 'center'});
		var mTd_oper = new Element('td', {'class': 'right'});
		mTd_file.grab((new Element('a',
			{id: parDir + '_N', 'class':'dnl',
			events : {click: doChdir.pass(parDir)}})
			).set('text','Parent Directory'));
		mTd_type.grab(new Element('img', {id: parDir + '_I', src: IMG_DIR_UP, 'class': 'middle'}));

		partr.grab(mTd_date).grab(mTd_size).grab(mTd_type).grab(mTd_file);
		if (h_refr) partr.grab(mTd_oper);
	}

	var arDir = new Array();
	var arFil = new Array();

	jj.dnl.each( function(tkn,i) {
		if (tkn.file != '') {
			var mTd_date;
			var mTd_size;

			if (! $(tkn.file + '_tr')) {
				    mTd_date = new Element('td', {id: tkn.file + '_date', 'class': 'right', width: 130});
				    mTd_size = new Element('td', {id: tkn.file + '_size', 'class': 'right', width: 50});
				var mTd_type = new Element('td', {'class': 'center', width: 40});
				var mTd_file = new Element('td', {'class': 'left'});
				var mTd_oper = new Element('td', {'id' : tkn.file, 'class': 'right', style:'width:192px'});
				var mTr = new Element('tr', {'id' : tkn.file + '_tr'}).addEvent('mouseover', fx_mover.bind(mTd_oper));

				if (tkn.type == 'd') {
					mTd_file.grab((new Element('a',
						{id: curDir + tkn.file + '_N', 'class':'dnl',
						'events' : {click: doChdir.pass(curDir + tkn.file)}})
						).set('text',' ' + tkn.file));
				} else {
					mTd_file.grab((new Element('a',
						{id: tkn.file + '_D', 'class':'dnl',
						href: ZDOWN + "?file=" + tkn.inode
						})).set('text',tkn.file));
					}

				if ((tkn.file.indexOf('.torrent') == tkn.file.length - 8) && (tkn.file.length > 7)) {
					mTd_oper.set('rel','T');
					}

				mime_type(mTd_type, tkn, curDir + tkn.file + '_I');
				mTr.grab(mTd_date).grab(mTd_size).grab(mTd_type).grab(mTd_file);
				if (h_refr) mTr.grab(mTd_oper);
				if (tkn.type == 'd')
					arDir.push(mTr);
				else
					arFil.push(mTr);
			} else {
				var im; if (im = $(tkn.file + '_T')) im.src = IMG_PLAY;
			}

			if (! mTd_date) {
				mTd_date = $(tkn.file + '_date');
				mTd_size = $(tkn.file + '_size');
			}
			mTd_date.set('text', tkn.date.split('.')[0].trim());
			if (tkn.type != 'd') mTd_size.set('text', m_humanReadable(tkn.size));
		}
	});

	arFil.each( function (ttr) { h_bDnl.grab(ttr, 'top'); });
	arDir.each( function (ttr) { h_bDnl.grab(ttr, 'top'); });

	if (b_chdir && partr) h_bDnl.grab(partr, 'top');
	b_chdir = false;

	zebra(h_bDnl);

	log.out('buildDnlList - done', jj.dnl.length);
	return jj;
}
function fx_mover(){
	if (h_refr && (tknfile!=this.id)) {
		if (tknfileObj) fx_hide();
		tknfile=this.id;
		tknfileObj=this;
		var mnus = this.getElements('.smallimg');
		if (mnus.length==0) {
			if (this.get('rel')=='T') {
				var imgM = new Element('img',
					{id: tknfile + '_M',
					src: IMG_PLAY,
					title: TIT_TIP,
					rel: TIT_PLAY,
					'class': 'pointer smallimg',
					styles: {width:'0px', height:'0px'},
					events: { 'click': m_request.pass(['meta', curDir + tknfile, tknfile + '_M', ZMETA, popCtor]) }});
				this.grab(imgM);

				var imgQ = new Element('img',
					{id: tknfile + '_Q',
					src: IMG_METAINFO,
					title: TIT_TIP,
					rel: TIT_METAINFO,
					'class': 'pointer smallimg',
					styles: {width:'0px', height:'0px'},
					events: { 'click': m_request.pass(['info', curDir + tknfile, tknfile + '_Q', ZMETA, popMeta]) }});
				this.grab(imgQ);
				}

			var imgR = new Element('img',
				{id: tknfile + '_R',
				src: IMG_RENAME,
				title: TIT_TIP,
				rel: TIT_RENAME,
				'class': 'pointer smallimg',
				styles: {width:'0px', height:'0px'},
				events: { 'click': popRename }});
			this.grab(imgR);

			var imgV = new Element('img',
				{id: tknfile + '_V',
				src: IMG_MOVETO,
				title: TIT_TIP,
				rel: TIT_MOVETO,
				'class': 'pointer smallimg',
				styles: {width:'0px', height:'0px'},
				events: { 'click': m_request.pass(['tree','treepop', tknfile + '_V', ZSTAT, popMove]) }})
			this.grab(imgV);
	;
			var imgW = new Element('img',
				{id: tknfile + '_W',
				src: IMG_STUFFIT,
				title: TIT_TIP,
				rel: TIT_STUFFIT,
				'class': 'pointer smallimg',
				styles: {width:'0px', height:'0px'}
				});
			imgW.addEvent("click", popConfirm.bindWithEvent(imgW, [MSG_STUFFIT,'targz',curDir + tknfile]));
			this.grab(imgW);

			var imgD = new Element('img',
				{id: tknfile + '_D',
				src: IMG_DELETE,
				title: TIT_TIP,
				rel: TIT_DELETE,
				'class': 'pointer smallimg',
				styles: {width:'0px', height:'0px'}
				});
			imgD.addEvent("click", popConfirm.bindWithEvent(imgD, [MSG_REMOVE,'rem',curDir + tknfile]));
			this.grab(imgD);
			iniTips();
			mnus = this.getElements('.smallimg');
		}
		mnus.each( function(img, i) {
			initAnimate.delay((5-i)*100,img,[img,'smallimg']);
			});
	}
}
function fx_hide(){
	if (tknfileObj) tknfileObj.getChildren().each( function(el,i){
		el.morph.delay(300-i*50,el,{width: "0px", height: "0px"});
		el.destroy.delay(500,el);
		});
}
function mime_type(td, tkn, myID) {
	if (tkn.type == 'd')
		return td.grab(new Element('img', {id: myID, src: IMG_DIR, 'class': 'middle smallimg'}));

	var ext = tkn.file.substr(tkn.file.lastIndexOf('.') + 1);
	if (MIME[ext] && tkn.file.indexOf('.') > 0)
		td.grab(new Element('img', {id: myID, src: MIME[ext], 'class': 'middle smallimg'}));
	else
		td.grab(new Element('img', {id: myID, src: MIME.or_else, 'class': 'middle smallimg'}));
}
var iniTips = function () {
	if (h_tips) {
		h_tips.detach('.pointer')
		h_tips.attach('.pointer')
	} else {
		h_tips = new Tips($$('.pointer'));
		h_tips.addEvent('show', function(tip, el){ tip.fade(0.9); });
		h_tips.addEvent('hide', function(tip, el){ tip.fade('out'); });
	}
}
function initAnimate(what,how){
	var allish=what.getElements('.' + how);
	if (allish.length != 0) return allish.each(function(el){ initAnimate(el,how); });
	if (!what.set) return;

 	what.set('morph',{duration:'short',transition:'bounce:out'});
	what.addEvents({
		'mouseover': function () { what.morph({"width": IMGS[how][1] + "px", "height": IMGS[how][1] + "px"}); },
		'mouseout': function () { what.morph({"width": IMGS[how][0] + "px", "height": IMGS[how][0] + "px"}); }
		});
	what.morph({"width": IMGS[how][0] + "px", "height": IMGS[how][0] + "px"});
}
var processor = function(t, tt){
	switch (t) {
	case undefined:
		log.init(register);
		curDir = Storage.read('curdir');
		if (!curDir) Storage.write('curdir', curDir='/');

		h_bDnl = $('bDnl');		h_sTrk = $('sTrk');		h_torrents = $('torrents');
		h_wgets = $('wgets');		h_disk = $('disk');		h_mta = $('mta');
		h_conf = $('mconf');		h_hlp = $('hlp');		h_sCur = $('spcurdir');
		h_freq = $('udmRefreshFreq');	h_mtain = $('mta_in');		h_nuke = $('nuke');
		h_refr = $('refr');		h_refr2 = $('refr2');		h_amule = $('udmChkAmule');

		$$('.persist').each(function (el){
			Storage.monitor(el);
			el.addEvent('keypress', h_mta.close);
			});

		$$('.btnOk').each(function (el){
			el.addEvent('click', Popup.hideAll);
			});
		$$('table.pop_up').each(Popup.init);

		if (h_refr) {
			h_refr.addEvent ('click', m_readData);
			h_freq.addEvent ('change', m_readData);
			$('openconf').addEvent('click', h_conf.show);
			$('btnDef').addEvent('click', popReset);
			$('btnBkp').addEvent('click', popBackup);
			$('disk_f').addEvent('click', m_request.pass(['disk', 'disk', 'disk_f', ZCMD, popDisk]));
			$('cmd').addEvent('click', popCmd);
			h_nuke.addEvent ('click', popConfirm.bindWithEvent(h_nuke, [MSG_NUKE,'nukeall','']));
			h_amule.addEvent('click', doAmure);
			$('openhelp').addEvent('click', h_hlp.show);
			h_sTrk.empty();

			$('go_down').addEvent('click',popWget);
			$('go_mu').addEvent('click',popMu);
			$('go_upl').addEvent('click' , function() { $('f_upl').submit(); });
			$('f_upl').set('action',Z2388);
			$('newdir').addEvent('click', popMkdir);

			mA = new multipleOpenAccordion($('a_main'), '.t_main', '.e_main', {
				display:1, allowMultipleOpen: true, initialDisplayFx: false,
				onActive: function(toggler, element){ toggler.setStyle('color', '#528CE0'); if (this.elements.indexOf(element)==1) m_readData()},
				onBackground: function(toggler, element){ toggler.setStyle('color', 'black');	}
				});

			new Accordion($('a_help'), '.t_help', '.e_help', {
				display: 1, initialDisplayFx: false,
				onActive: function(toggler, element){ toggler.setStyle('color', 'white'); },
				onBackground: function(toggler, element){ toggler.setStyle('color', '#528CE0');	}
				});

			new Accordion($('a_settings'), '.t_settings', '.e_settings', {
				display: 3,
				onActive: function(toggler, element){ toggler.setStyle('color', 'white'); if (element.id=='sec_in') m_request('lock', 'read', 'lock', ZCMD, popLock) },
				onBackground: function(toggler, element){ toggler.setStyle('color', '#528CE0'); }
				});
		}

		$('viewtree').addEvent('click', m_request.pass(['tree', 'treepop', 'viewtree', ZSTAT, popTree]));
		h_refr2.addEvent ('click', m_readData);

		$$('.nav').each(function(el){
 			el.set('tween',{duration:'short',transition:'bounce:out'});
			el.set('tween',{duration:'short'});
			el.addEvents({
				'mouseover': function () { el.tween('font-size', '14px'); },
				'mouseout': function () { el.tween('font-size', '12px'); }
				});
			});

		new SortingTable( 'sDnl', {
			zebra: false,
			forward_sort_class: 'forward_sort',
			reverse_sort_class: 'reverse_sort',
			onSorted: function (){ zebra(h_bDnl)}
			});

		iniTips();
		initAnimate(document, 'bigimg');
		initAnimate(document, 'smallimg');
		initAnimate(document, 'tinyimg');
		$('header').addEvent('mouseover', fx_hide);
		b_chdir = true;
		m_readData();
		break;

	case 'read':
		if (arguments[2]!=register.track)
			return log.out('processor', ' CANCELLED read: my reg:' + arguments[2]);

		var jj = buildDnlList(tt);
		if (!jj) {
			log.out('processor - read','buildDnlList did not return jj, calling m_readData');
			return m_readData.delay(5000);
			}

		h_refr2.src=IMG_REFRESH2;
		if (h_refr) {
			h_sTrk.getChildren().each( function(mTr) {
				if (tt.indexOf(mTr.id.substr(0,mTr.id.length-3)) < 0) mTr.destroy();
				if (mTr.id == AMULE_ID)   if (!h_amule.checked) mTr.destroy();
				});
			zebra(h_sTrk);
			h_refr.src=IMG_REFRESH;
			h_nuke.src=IMG_NUKE;
			h_torrents.set('text', jj.torrents);
			h_wgets.set('text', jj.wgets);
			m_getTrk(jj, 'nfo', 0, parseFloat(register.track.toString()));
		}
		iniTips();
		break;

	case 'trk':
		if (arguments[5]!=register.track)
			return log.out('processor', ' CANCELLED m_getTrk: my reg:' + arguments[5]);

		var jj =arguments[1];		var trk=arguments[2];
		var idx=arguments[3];		var reg=arguments[5];
		var obj=arguments[4].response.text.replace(/\r/g,'\n').split('\n');

		var fil = jj[trk][idx].obj.split('@')[0];
		var pid = jj[trk][idx].obj.split('@')[1];
		var msg = '';

		var p_todo = 208.0; // 100%
		switch (trk) {
			case 'wgt':
				for (var i=obj.length-1; (i>0) && (msg.length == 0); i--)
					if (obj[i] != '') msg = obj[i];
				if ((msg.indexOf('[') > 0) && (msg.indexOf('saved [')<0) && (msg.indexOf('saved[')<0)) {
					var sPro = msg.indexOf("[");
					var ePro = msg.indexOf("]");
					var pBar = msg.substring(sPro+1,ePro-1).replace(/ /g,"^");
					var pLen = p_todo / pBar.length;
					var p_old = lunghez(pBar,'+') * pLen;
					var p_don = lunghez(pBar,'=') * pLen;
					var p_new = lunghez(pBar,'>') * pLen;
					var p_ava = lunghez(pBar,'^') * pLen;
					if (pid=='') {
						p_old += p_don + p_new;
						p_don = p_new = 0;
						}
					msg = PROGRESS_TOT.replace('SPA',p_todo).replace('OLD',p_old).replace('DON',p_don).replace('NEW',p_new).replace('AVA',p_ava).replace('EMP',0) + msg.substring(0,sPro-1) + msg.substring(ePro+1);
				}
				msg = obj[0] + '<br>' + msg;
				var cold = ((pid=='') || (msg.indexOf('saved[')>0) || (msg.indexOf('saved [')>0) || (msg.indexOf('nothing to do')>0));
				break;
			case 'tor':
				for (var i=obj.length-1; (i>0) && (msg.length == 0); i--)
					if (obj[i] != '') msg = obj[i];
				if (msg.indexOf('[') > 0) {
					var sPro = msg.indexOf("[");
					var ePro = msg.indexOf("]");
					var comp = msg.substring(sPro+1,ePro).split("/");
					var p_curs = 1;
					var p_done = (comp[0] * p_todo) / comp[1];
					var p_disp = (comp[2] * p_todo) / comp[1] - p_done;
					var p_rest = p_todo - p_done - p_disp;
					if (p_done < p_todo)
						msg = PROGRESS_TOT.replace('SPA',p_todo).replace('OLD',(pid=='' ? p_done : 0)).replace('DON',(pid!='' ? p_done : 0)).replace('NEW',p_curs).replace('AVA',(pid=='' ? 0 : p_disp)).replace('EMP',(pid=='' ? p_rest + p_disp : p_rest)) + msg;
				}
				msg = obj[0] + '<br>' + msg;
				var cold = (pid=='');
				break;
			case 'amu':
				if (arguments[4].response.text.length == 0) {
					log.out('processor - trk','amu - response is empty, calling m_readData');
					return m_readData.delay(3000);
					}
				if (arguments[4].response.text.indexOf('>') < 0)
					msg=arguments[4].response.text.replace(/\n/g,'<br>');
				else {
					msg += '<table>';
					for (var i=0; i<obj.length; i++) {
						if (obj[i].trim().indexOf('>') == 0) {
							var fkn=obj[i].trim().substr(1).split(' ')[1];
							msg += '<tr><td>'
							msg += '<img src="images/ministop.png" class="pointer tinyimg stop" alt="cancel ' + fkn + '" title="&micro;dm" rel="cancel the download">'
							msg += ' <img src="images/minipause.png" class="pointer tinyimg pause" alt="pause ' + fkn + '" title="&micro;dm" rel="pause the download">'
							msg += ' <img src="images/miniplay.png" class="pointer tinyimg play" alt="resume ' + fkn + '" title="&micro;dm" rel="start the download"> '
							msg += obj[i].trim().substr(1).split(' ')[2] + '<br>';
							var perc=obj[i+1].trim();
							if (perc.indexOf('[') > 0) {
								var sPro = perc.indexOf("[");
								var ePro = perc.indexOf("%");
								var pBar = perc.substring(sPro+1,ePro-1).toInt() * p_todo / 100;
								msg += PROGRESS_TOT.replace('SPA',p_todo).replace('OLD',0).replace('DON',pBar).replace('NEW',1).replace('AVA',p_todo-pBar-1).replace('EMP',0);
							}
							msg += obj[i+1].trim().substr(1) + '</tr></td>';
							i++;
						}
					}
					msg += '<table>';
				}
				break;
			case 'nfo':
				msg = arguments[4].response.text.replace(/\r/g,'<br>').replace(/\n/g,'<br>');
				break;
		}

		if ((trk == 'tor') || (trk == 'wgt')) {
			var btnImage=( cold ? IMG_PLAY : IMG_STOP );
			var btnTitle=( cold ? TIT_PLAY : TIT_STOP );
		}

		tkn = fil.replace('.','');
		var h_p = h_sTrk.getElement('.' + tkn + '_T');
		var mTr;
		if (! h_p) {
			mTr = new Element('tr', {id: fil + '_tr', 'class' : tkn + '_tr ' + m_getClass(h_sTrk.getChildren().length)});
			var mTd_play = new Element('td', {'width' : '80', 'class': 'center' });
			var mTd_trak = new Element('td', {'width' : '*' });
			var mTd_oper = new Element('td', {'width' : '40' });
			var img_dele = new Element('img', {src: IMG_DELETE, title: TIT_TIP, rel: TIT_DELETE, 'class': 'pointer smallimg'});
			if (trk == 'nfo') {
				img_dele.addEvent('click', popConfirm.bindWithEvent(img_dele, [MSG_INFO,'del', fil]));
				h_p = new Element('img', {src: IMG_INFO, 'class': tkn + '_T smallimg'});
				mTd_play.grab(h_p);
			} else if (trk == 'amu') {
				img_dele = new Element('span');
				h_p = new Element('img', {src: IMG_AMULE, title: TIT_TIP, rel: TIT_AMULE, 'class': tkn + '_T pointer smallimg'});
				h_p.addEvent('click', popAmule);
				h_b = new Element('br');
				h_amuf = new Element('select', { id:'udmAmuleFreq',
								'class':'persist refresh pointer',
								title: TIT_TIP,
								rel: 'refresh interval:\nyou should keep this as long as possible\nnot to burden the server...',
								events : {change: doAmure}});
				h_amuf.grab(new Element('option', { 'value': 'manual', 'text':'manual', 'class':'pointer' }));
				h_amuf.grab(new Element('option', { 'value': '10000', 'text':'10 sec', 'class':'pointer' }));
				h_amuf.grab(new Element('option', { 'value': '60000', 'text':'1 min', 'class':'pointer' }));
				mTd_play.grab(h_p).grab(h_b).grab(h_amuf);
				if (mA.isOpen(1) && h_amule.checked) doAmure(document);
			} else {
				img_dele.addEvent('click', popConfirm.bindWithEvent(img_dele, [MSG_DELETE,'del', fil]));
				h_p = new Element('img', {src: btnImage, title: TIT_TIP, rel: btnTitle, 'class': tkn + '_T pointer smallimg'})
				mTd_play.grab(h_p);
				mTd_play.grab(new Element('img', {
						id: tkn + '_F',
						src: IMG_METAINFO,
						title: TIT_TIP,
						rel: TIT_TRKINFO,
						'class': tkn + '_F pointer smallimg',
						events: { 'click': doViewCmdLine }
						}));
				}
			mTd_oper.grab(img_dele);
			mTd_trak.grab(new Element('div', {html: msg, 'class': tkn + ' tracker'}));
			mTr.grab(mTd_play);
			mTr.grab(mTd_trak);
			mTr.grab(mTd_oper);
			h_sTrk.grab(mTr);
			initAnimate(mTd_play, 'smallimg');
			initAnimate(mTd_oper, 'smallimg');
			iniTips();
		} else {
			if ((trk == 'tor') || (trk == 'wgt')) {
				var oldImg = h_p.get('src');
				h_p.set('src', btnImage);
				h_p.set('title', TIT_TIP);
				h_p.set('rel', btnTitle);
				if (oldImg != btnImage) {
					log.out('processor - trk','oldImg != btnImage - calling m_readData');
					return m_readData();
				}
			}
			h_sTrk.getElement('.' + tkn).set('html',msg);
			mTr=h_p.getParent().getParent();
		}

		if ((trk == 'tor') || (trk == 'wgt')) {
			var pars=new Array();
			pars.push( cold ? MSG_STARTDNL : MSG_STOPDNL );
			pars.push( cold ? (trk == 'tor' ? 'starttor' : 'startdnl') : 'stop' );
			pars.push( fil );
			h_p.removeEvents('click');
			h_p.addEvent('click', popConfirm.bindWithEvent(h_p, pars));
		}
		if (trk=='amu')
			mTr.getElements('.tinyimg').each(function(i){
				initAnimate(i, 'tinyimg');
				i.addEvent('click', doAmule);
			});

		m_getTrk(jj, trk, ++idx, reg);
		mA.resize.delay(1000,mA,1);

		break;
	}
}

function lunghez(wha, ch) { return ( wha.indexOf(ch)<0 ? 0 : wha.lastIndexOf(ch)-wha.indexOf(ch) +1 ); }

///////////////////
// POPUP actions //

function doMkdir(cmd, newID) {
	var fina = newID.value;
	if (!fina || fina=='') return;

	if (fina.indexOf("/") < 0) fina = curDir + fina;
	m_ajax('cmd=' + cmd + '&file=' + escape(fina));
}

function doRename(cmd, myID, newID) {
	var fina = newID.value;
	if (!fina || fina=='') return;

	if (fina.indexOf("/") < 0) fina = curDir + fina;
	if (fina.charAt(fina.length-1) == '/') fina += myID;
	m_ajax('cmd=' + cmd + '&file=' + escape(curDir + myID) + '&para=' + escape(fina));
}

function doViewCmdLine() {
	var typ = (this.id.substr(0,3) == 'tor' ? 'tor' : 'log' );
	var fil = (typ == 'tor' ? this.id.substring(3, 9) : this.id.substring(0, 6) );
	m_request('opts', fil, this.id, 'trk/' + fil, popOpts.bind(this));
}

function doChdir(cd) {
	var myCur;
	if ($type(cd)=='string'){
		myCur = cd;
		$(cd + '_I').set('src', IMG_SPINNER);
	} else
		myCur = cd.value
	if (!myCur)
		return h_mta.hide;

	curDir = (myCur + '/').replace(/\/\//g,'/');
	Storage.write('curdir', curDir);
	Popup.hideAll();
	b_chdir = true;
	log.out('doChdir','Calling m_readData');
	m_readData();
}

function doLock() {
	var usn=$('usn').value +':' + encode64($('psd').value) + ':' + ($('ufb').checked?1:0);
	var finish=function (t){ register.changeTrack('doLock()'); popMsg(t); }
	m_request('lock', usn, 'lock', ZCMD, finish);
}

function doMu(){
	m_ajax('cmd=mu&file=' + escape($('mufile').value) + '&para=' + escape('login=1&next=c%3Daccount&username=' + h_mta.getElement('.muuser').value + '&password=' + h_mta.getElement('.mupass').value))
}

function doCmd(e) {
	if 	($type(e)=='string')	h_mta.getElement('.outi').value = e;
	else if ( e.key == 'enter' )	m_request(this.get('rel'), this, this.get('rel'), ZCMD, doCmd);
}

function doAmule(e) {
	if 	($type(e)=='string') {
		popMsg(e);
		log.out('doAmule','$type(e)==string, calling m_readData');
		m_readData();
		}
	else 	m_request('amule', this.alt, 'amule', ZCMD, doAmule);
}

function doAmure(rt){
	if (!h_amule.checked) {
		log.out('doAmure','!h_amule.checked, calling m_readData');
		return m_readData();
		}
	if (!mA.isOpen(1)) {
		log.out('doAmure','!mA.isOpen(1), calling m_readData');
		return m_readData();
		}

	var fromClic = $type(rt) != 'number';
	if (!fromClic && h_amuf) if (isNaN(h_amuf.value)) {
		log.out('doAmure','(h_amuf) && (isNaN(h_amuf.value)), calling m_readData');
		return m_readData();
		}

	var tkn = fromClic ? reg_amu.changeTrack() : rt;
	if ((reg_amu.track != tkn)) return;

	m_request('amure', tkn, 'amule', ZCMD, doAmure_post.pass([fromClic, tkn]));
}

function doAmure_post(fromClic, tkn){
	if (fromClic) {
		log.out('doAmure_post','Was fromClic, calling m_readData');
		m_readData();
		}
	if (h_amuf) if (!isNaN(h_amuf.value)) doAmure.delay(h_amuf.value,h_amuf,tkn);
}

function doScript(e) {
	var v=h_mtain.getElement('#selcmd').value;
	if (v!='') m_request('scripts', v, 'scripts', ZCMD, doCmd);
}

function doSubmit(e) {
	if ( e.key == 'enter' )	return h_mta.getElement('.btnOk').click();
	if ( e.key == 'esc' )	return h_mta.getElement('.btnCancel').click();
}

////////////////////////////
// AJAX SERVER INTERFACES //

function m_readData(rt) {
	var fromClic = ($type(rt) == 'event');
	if (rt && (rt != register.track) && (!fromClic)) return log.out('m_readData','CANCELED for register.changeTrack of type ' + $type(rt));
	else 							log.out('m_readData','ok: ' + register.track);

	register.changeTrack();
	if (h_refr) h_refr.src=IMG_SPINNER_BIG;
	if (h_refr2) h_refr2.src=IMG_SPINNER;

	if (fromClic) {
		d_tree=null;
		if (h_amule.checked && mA.isOpen(1) && h_amuf) if (isNaN(h_amuf.value)) return doAmure(document);
		}

	var qs; // querystring
	if (mA) qs='f='+(mA.isOpen(2)?1:fromClic?1:0)+'&t='+(mA.isOpen(1)?1:fromClic?1:0);
	else qs='f=1&t=0';

	var rq = newReq('m_readData', ZSTAT);
	rq.onSuccess  = function(t){ processor('read', t, register.track)};
	rq.send(qs);
}

function m_getTrk(jj, trk, idx, reg) {
	var fnc='m_getTrk';
	log.out(fnc,trk + " " + idx + " " + reg + " " + trk + " " + idx);
	if (reg!=register.track) return;

	if ((!jj[trk]) || (!jj[trk][idx]))
		switch (trk) {
			case 'nfo': return h_amule.checked ? m_getTrk(jj, 'amu', 0, reg) : m_getTrk(jj, 'wgt', 0, reg); break;
			case 'amu': return m_getTrk(jj, 'wgt', 0, reg); break;
			case 'wgt': return m_getTrk(jj, 'tor', 0, reg); break;
			case 'tor': if (!isNaN(h_freq.value)) {
						log.out('m_getTrk','New cycle: calling m_readData in ' + h_freq.value/1000 + ' seconds');
						return m_readData.delay(h_freq.value, h_refr, register.track); break;
				    } else { 	return; }
			default:    popError('Unknown typo'); break;
		}
	var tk = jj[trk][idx].obj.split('@')[0];
	var rq = newReq(fnc, 'trk/' + tk);
	rq.onSuccess=processor.pass(['trk', jj, trk, idx, rq, reg]);
	rq.send();
}

function m_ajax(arg, m_bind) {
	var fnc='m_ajax';
	log.out(fnc,arg);

	if (m_bind) m_bind.src=IMG_SPINNER;
	Popup.hideAll();
	register.changeTrack(fnc + '(' + arg + ')');
	var rq = newReq(fnc, ZCMD);
	rq.onSuccess = function(t){
		if (t.indexOf('OK') < 0) popError(t);
		log.out('m_ajax', 'After rq.onSuccess - calling m_readData');
		m_readData();
		}
	rq.send(arg);
}

function m_request(cmd, file, m_bind, m_url, m_callback){
	var fnc='m_request';
	log.out(fnc, '(' + cmd + ' ,' + file + ' ,' + m_bind + ')');

	if ($(m_bind)) $(m_bind).set('src', IMG_SPINNER);
	ff= ($type(file)=='string' ? file : file.value);

	if (cmd == 'tree') {
		h_t = m_bind.substr(0,m_bind.length-2);
		if (d_tree && m_callback) return m_callback.delay(50, d_tree);
		}

	var rq = newReq(fnc, m_url);
	if (m_callback) rq.onSuccess = m_callback.bind($(m_bind));
	rq.send('cmd=' + cmd + '&file=' + escape(ff));
}

function m_composeCmdLine(cmd, file){
	var para = '';
	h_mta.getElements('.field').each(		function(fld){ if (fld.value!='') para += ' ' + (OPT[fld.get('rel')]?OPT[fld.get('rel')]:fld.get('rel')) + ' ' + m_format_field(fld.value); });
	h_mta.getElements('.field_check').each( 	function(fld){ if (fld.checked)   para += ' ' + (OPT[fld.get('rel')]?OPT[fld.get('rel')]:fld.get('rel')); });
	h_mta.getElements('.field_file[checked]').each( function(fld, idx){ 		  para += (idx == 0 ? ' -n ' : ',') + fld.value; });
	m_ajax('cmd=' + cmd + '&file=' + escape($(file).value) + '&para=' + escape(para));
}

function newReq(fnc, m_url) {
	var rq = new Request({url: m_url});
	rq.onRequest= function(){ log.out(fnc,'REQUEST'); }
	rq.onCancel = function(){ log.out(fnc,'CANCELED'); }
	rq.onFailure= function(){ log.out(fnc,'FAILED - calling m_readData in 5 secs'); register.changeTrack('m_readData FAILED'); m_readData.delay(5000); }
	return rq;
}
////////////////
// FORMATTING //

function m_format_field(s) {
	var o = s;
	if (!(s.indexOf('"') < 0)) o = o.replace('"','\\"');
	if (!(s.indexOf(' ') < 0)) o = '\"' + o + '\"';
	return o;
}
function m_humanReadable(s) { return (s>1073741824) ? parseInt(s/1073741824,10) + " GB" : (s>1048576) ? parseInt(s/1048576,10) + " MB" : (s>1024) ? parseInt(s/1024,10) + " KB" : s; }
function m_getClass(i) { return (i & 1) ? 'tdtrk2' : 'tdtrk1'}
function zebra(wha) { wha.getChildren().each( function(mTr,i) { mTr.set('class', m_getClass(i)); }); }
/////////////
// GLOBALS //
var curDir;
var partr;
var b_chdir = false;
var d_tree;
var version='0.4.1';
var tknfile;
var tknfileObj;
var AMULE_ID='amule.amu_tr';
//////////////////
// HTML objects //
var h_nuke;	var h_bDnl;	var h_torrents;	var h_wgets;	var h_disk;	var h_refr;	var h_refr2;
var h_freq;	var h_lim;	var h_mta;	var h_conf;	var h_hlp;	var h_amule;	var mA;
var h_f; 	var h_t;	var h_sCur;	var h_mta_in;	var h_tips;	var h_amuf;
////////////
// IMAGES //
var IMG_SPINNER_BIG	='images/spinner_big.gif';
var IMG_DELETE		='images/delete.png';
var IMG_STUFFIT		='images/stuff.png';
var IMG_METAINFO	='images/lens.png';
var IMG_PLAY		='images/play.png';
var IMG_DISK		='images/disk.png';
var IMG_OPTIONS		='images/options.png';
var IMG_RENAME		='images/rename.png';
var IMG_MOVETO		='images/moveto.png';
var IMG_STOP		='images/stop.png';
var IMG_SPINNER		='images/spinner.gif';
var IMG_REFRESH		='images/refresh.png';
var IMG_REFRESH2	='images/refresh2.png';
var IMG_NUKE		='images/nuke.png';
var IMG_DIR		='images/directory.png';
var IMG_DIR_UP		='images/directory_up.png';
var IMG_TREE		='images/tree.png';
var IMG_NEW		='images/new.png';
var IMG_INFO		='images/info.png';
var IMG_AMULE		='images/amule/amule.png';
var IMG_CONF		='images/conf.png';
var IMGS = new Array();
IMGS['tinyimg']=[14,16];
IMGS['smallimg']=[28,32];
IMGS['bigimg']=[42,48];
////////////////////
// Image tooltips //
var TIT_TIP		='&micro;dm';
var TIT_PLAY		='start the download';
var TIT_STOP		='pause the download';
var TIT_STUFFIT		='compress to tar.gz';
var TIT_RENAME		='rename';
var TIT_MOVETO		='move or copy to another folder';
var TIT_METAINFO	="display the torrent's metainfo";
var TIT_TRKINFO		="display the tracker's info";
var TIT_DELETE		='delete file or tracker';
var TIT_AMULE		='open aMule popup';
//////////////
// MESSAGES //
var MSG_DELETE		="Delete the tracker?\n(ATTN: the download operation will be canceled as well)";
var MSG_DEL_AMULE	="Delete the tracker?\n(ATTN: if aMule is running, it will not be stopped)";
var MSG_STUFFIT		="Create \"$$$.tar.gz\"?";
var MSG_INFO		="Delete the message?";
var MSG_REMOVE		="Remove \"$$$\"?";
var MSG_STARTDNL		="Restart the download?";
var MSG_STOPDNL		="Stop the download?";
var MSG_NUKE		="Nuke all ctorrents and wgets, delete all trackers?\n(only downloaded and partially downloaded files will not be deleted)";
////////////////////////////
// Coloured progress bars //
var PROGRESS_TOT='<span style="width:SPApx" class="progress">' +
	'<img src="images/transparent.gif" style="width:OLDpx" class="progress blu">'+
	'<img src="images/transparent.gif" style="width:DONpx" class="progress red">'+
	'<img src="images/pnew.png" style="width:NEWpx" class="progress">'+
	'<img src="images/transparent.gif" style="width:AVApx" class="progress gre">'+
	'<img src="images/transparent.gif" style="width:EMPpx" class="progress gra"></span> ';
///////////////
// CGI files //
var ZCMD='cgi-bin/udm-cmd.cgi';
var ZDOWN='cgi-bin/udm-down.cgi';
var ZMETA='cgi-bin/udm-benc.cgi';
var ZSTAT='cgi-bin/udm-stat.cgi';
var Z2388='cgi-bin/udm-2388.cgi';
////////////////
// Mime table //
var MIME=new Object();
MIME.exe="images/mime/app.png"
MIME.mp3=MIME.m3u=MIME.wav=MIME.aif=MIME.aifc=MIME.aiff=MIME.aim=MIME.au=MIME.m2a=MIME.mid=MIME.midi=MIME.mod=MIME.mpga=MIME.ra=MIME.ram=MIME.rpm="images/mime/mp3.png"
MIME.doc="images/mime/word.png"
MIME.txt=MIME.log=MIME.rtf=MIME.latex=MIME.rt=MIME.rtx=MIME.tex=MIME.text=MIME.word="images/mime/doc.png"
MIME.swf=MIME.fla=MIME.flv="images/mime/flash.png"
MIME.jpg=MIME.gif=MIME.png=MIME.bmp=MIME.ico=MIME.jpeg=MIME.pbm=MIME.pct=MIME.pcx=MIME.pgm=MIME.tif=MIME.tiff=MIME.ani="images/mime/img.png"
MIME.pdf="images/mime/pdf.png"
MIME.ppt=MIME.pps=MIME.ppa="images/mime/ppt.png"
MIME.mpg=MIME.mpeg=MIME.mkv=MIME.vob=MIME.ifo=MIME.bup=MIME.mpa=MIME.mov=MIME.avi=MIME.asf=MIME.qt=MIME.rm=MIME.ram=MIME.mv=MIME.afl=MIME.asx=MIME.avs=MIME.fli=MIME.dvi=MIME.gl=MIME.m1v=MIME.m2v=MIME.mjpg=MIME.moov=MIME.movie=MIME.mp2="images/mime/mov.png"
MIME.htm=MIME.html=MIME.asp=MIME.css=MIME.js=MIME.shtml=MIME.vrml="images/mime/web.png"
MIME.xls=MIME.xla="images/mime/xls.png"
MIME.zip=MIME.rar=MIME.arj=MIME.bz=MIME.bz2=MIME.gz=MIME.tgz=MIME.tar=MIME.gzip=MIME.uu=MIME.z=MIME.uue=MIME.lzh=MIME.lzx=MIME.lha=MIME.sit="images/mime/zip.png"
MIME.iso=MIME.nrg=MIME.cue=MIME.ccd="images/mime/iso.png"
MIME.torrent="images/mime/torrent.png"
MIME.or_else="images/mime/else.png"
/////////////
// OPTIONS //
OPT={"wgetLimitRate":"--limit-rate","wgetTries":"-t","wgetContinue":"-c","wgetUser":"--user","wgetPass":"--pass","wgetAuthNoChallenge":"--auth-no-challenge","wgetReferer":"--referer","wgetHeader":"--header",
"wgetSaveHeader":"--save-header","wgetUserAgent":"--user-agent","wgetNoCookies":"--no-cookies","wgetSaveCookies":"--save-cookies","wgetLoadCookies":"--load-cookies","wgetKeepSessionCookies":"--keep-session-cookies",
"wgetPostData":"--post-data","wgetPostFile":"--post-file","wgetRecursive":"-r","wgetNoParent":"-np","wgetOutputDocument":"-O",
"ctorMaxDLrate":"-D","ctorMaxULrate":"-U","ctorCacheSize":"-C","ctorSeedHours":"-e","ctorSeedRatio":"-E","ctorPublicIPAddress":"-I",
"ctorMaxPeers":"-M","ctorMinPeers":"-m","ctorSliceSize":"-z","ctorUserAgent":"-A","ctorHostAndPort":"-S","ctorPreallocate":"-a","ctorAlternateAnnounce":"-u","ctorListenPort":"-p","ctorCommand":"-X","ctorSaveAs":"-s"}
/////////////
// ACTION! //
window.addEvent('domready', processor);
